import router from '@/router';

import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { loadFromLocal } from '@/utils/cache';
import getPageTitle from './utils/getPageTitle';
import { getToken } from './utils/auth';
import store from './store/index';

NProgress.configure({ showSpinner: false });

const whiteList = ['/login', '/home', '/user/service'];

router.beforeEach(async (to, from, next) => {
  NProgress.start();

  // set page title
  document.title = getPageTitle(to.meta.title);

  // determine whether the user has logged in
  const hasToken = getToken();

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' });
      NProgress.done();
    } else {
      const hasInfo = loadFromLocal('userInfo', 'nfUser', false);
      if (hasInfo) {
        next();
      } else {
        await store.dispatch('user/resetToken');
        next(`/login?redirect=${to.path}`);
        NProgress.done();
      }
    }
  } else {
    /* has no token */
    // eslint-disable-next-line no-lonely-if
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});
